using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace SmartLink.Infrastructure
{
    public class JWTHelper
    {
        public static string GenToken(int userId,bool isXCX)
        {
            //SymmetricSecurityKey symmetricSecurityKey = KeyingMaterial.DefaultSymmetricSecurityKey_256;
            //var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);

            JwtHeader header = new JwtHeader(KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2);
            JwtPayload payLoad = new JwtPayload();
            payLoad.Add("iss", "");
            payLoad.Add("sub", "");
            payLoad.Add("dept", "");
            payLoad.Add("userid", userId);
            payLoad.Add("IsXCX", isXCX);
            var ExpiresTime = DateTime.Now.AddSeconds(ConstData.ExpirsTimes);
            payLoad.Add("expires", TimeHelper.GetUnixTime(ExpiresTime));


            //SigningCredentials signingCredentials = new SigningCredentials(rsaSecurityKey,);
            //string rawHeader = header.Base64UrlEncode();
            //string rawPayload = payload.Base64UrlEncode();
            //string rawSignature = signingCredentials == null ? string.Empty : CreateEncodedSignature(string.Concat(rawHeader, ".", rawPayload), signingCredentials);
            //CreateEncodedSignature(string.Concat(rawHeader, ".", rawPayload), signingCredentials)

            JwtSecurityToken jToken = new JwtSecurityToken(header,payLoad);
            EncryptingCredentials en =  jToken.EncryptingCredentials;


            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jToken);
            return encodedJwt;
        }

        public static JwtSecurityToken DecodeToken(string token)
        {
            JwtSecurityToken reToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
            return reToken;
        }

   
        public static int GetUserIdFromToken(string token)
        {
            JwtSecurityToken reToken = DecodeToken(token);
            return Convert.ToInt32(reToken.Payload["userid"]);
        }

        public static bool GetIsAppFromToken(string token)
        {
            bool isApp= false;
            JwtSecurityToken reToken = DecodeToken(token);
            Dictionary<string, object> payLoadDic =(Dictionary<string, object>)reToken.Payload;
            if(payLoadDic.ContainsKey("IsApp"))
                isApp =reToken.Payload["IsApp"].ToString() =="true"?true:false;

            return isApp;
        }

        public static long ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks);
            return t;
        }

    }
}
